package com.idopartx.phonelightning.ui.home.screen

import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import android.graphics.Path
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.dotools.umlibrary.UMPostUtils
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.idopartx.phonelightning.R
import com.idopartx.phonelightning.common.Constant
import com.idopartx.phonelightning.databinding.ActivityScreenLightningBinding
import com.idopartx.phonelightning.entity.ScreenLightningEntity
import com.idopartx.phonelightning.ui.adapter.ScreenSelectAdapter
import com.idopartx.phonelightning.ui.base.BaseActivity
import com.idopartx.phonelightning.ui.home.smslightning.SmsLightningActivity
import com.idopartx.phonelightning.utils.GridSpaceItemDecoration
import com.idopartx.phonelightning.viewmodel.ScreenViewModel
import com.idopartx.phonelightning.widget.ColorPickerView
import com.tencent.mmkv.MMKV
import com.wuhenzhizao.titlebar.widget.CommonTitleBar
import java.util.HashMap

class ScreenLightningActivity : BaseActivity<ActivityScreenLightningBinding>() {


    private val viewModel: ScreenViewModel by lazy {
        ViewModelProvider(this).get(ScreenViewModel::class.java)
    }

    private val mAdapter: ScreenSelectAdapter by lazy {
        ScreenSelectAdapter(onItemClick = {
            viewModel.typeLiveData.value = it.type
            when (it.type) {
                0 -> {
                    binding.rgDirection.check(if (viewModel.directionLiveData.value == Path.Direction.CCW) R.id.rb_left else R.id.rb_right)
                    binding.viewLine.type = 0
                    binding.ksbLength.setProgress(it.length?.toFloat() ?: 1f)
                    binding.ksbWidth.setProgress(it.width?.toFloat() ?: 1f)
                    binding.ksbSpeed.setProgress(it.speed?.toFloat() ?: 1f)

                }
                1 -> {
                    binding.rgDirection.check(if (viewModel.directionLiveData.value == Path.Direction.CCW) R.id.rb_left else R.id.rb_right)
                    binding.viewLine.type = 1
                    binding.ksbLength.setProgress(it.length?.toFloat() ?: 1f)
                    binding.ksbWidth.setProgress(it.width?.toFloat() ?: 1f)
                    binding.ksbSpeed.setProgress(it.speed?.toFloat() ?: 1f)
                }

                2 -> {
                    binding.ksbWidth.setProgress(it.width?.toFloat() ?: 1f)
                    binding.ksbLightingSpeed.setProgress(it.speed?.toFloat() ?: 1f)
                }

                3 -> {
                    binding.ksbWidth.setProgress(it.width?.toFloat() ?: 1f)
                    binding.ksbLightingSpeed.setProgress(it.speed?.toFloat() ?: 1f)
                    binding.viewColorPicker.setPosition(it.x, it.y)
                    viewModel.colorLiveData.value?.let { color -> binding.viewBreath.setColor(color) }

                }
            }

            binding.viewModel = viewModel


        })
    }

    override fun initLayoutResId(): Int {
        return R.layout.activity_screen_lightning
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        viewModel.init()

        binding.viewTitleBar.setListener { v, action, _ ->
            when (action) {
                CommonTitleBar.ACTION_RIGHT_TEXT -> {
                    if (v is TextView) {
                        getCanDrawOverlays()
                    }
                }

                CommonTitleBar.ACTION_LEFT_BUTTON -> {
                    finish()
                }
            }
        }


        binding.viewColorPicker.apply {
            setOnColorPickerChangeListener(object : ColorPickerView.OnColorPickerChangeListener {
                override fun onColorChanged(picker: ColorPickerView?, color: Int, x: Int, y: Int) {
                    viewModel.colorLiveData.value = color
                    viewModel.xLiveData.value = x
                    viewModel.yLiveData.value = y
                    binding.viewBreath.setColor(color)
                }

                override fun onStartTrackingTouch(picker: ColorPickerView?) {

                }

                override fun onStopTrackingTouch(picker: ColorPickerView?) {

                }

            })
        }

        binding.switchDelete.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                UMPostUtils.onEvent(applicationContext, "call_screen_switch_on")
            }
        }

        binding.rvSelect.layoutManager = GridLayoutManager(this, 4)
        binding.rvSelect.adapter = mAdapter
        val screenList = arrayListOf<ScreenLightningEntity>()

        screenList.add(ScreenLightningEntity(0, viewModel.typeLiveData.value == 0))
        screenList.add(ScreenLightningEntity(1, viewModel.typeLiveData.value == 1))
        screenList.add(ScreenLightningEntity(2, viewModel.typeLiveData.value == 2))
        screenList.add(ScreenLightningEntity(3, viewModel.typeLiveData.value == 3))

        screenList[viewModel.typeLiveData.value ?: 0].direction = viewModel.directionLiveData.value

        binding.rgDirection.check(if (viewModel.directionLiveData.value == Path.Direction.CCW) R.id.rb_left else R.id.rb_right)
        viewModel.directionLiveData.value?.let {
            binding.viewLine.direction = it
        }

        binding.viewLine.type = if (viewModel.typeLiveData.value == 0) 0 else 1

        screenList[viewModel.typeLiveData.value ?: 0].speed = viewModel.speedLiveData.value

        screenList[viewModel.typeLiveData.value ?: 0].width = viewModel.widthLiveData.value

        screenList[viewModel.typeLiveData.value ?: 0].length = viewModel.lengthLiveData.value

        screenList[viewModel.typeLiveData.value ?: 0].color = viewModel.colorLiveData.value

        screenList[viewModel.typeLiveData.value ?: 0].x = viewModel.xLiveData.value ?: 0

        screenList[viewModel.typeLiveData.value ?: 0].y = viewModel.yLiveData.value ?: 0

        mAdapter.setList(screenList)

        binding.rgDirection.setOnCheckedChangeListener { group, checkedId ->
            binding.viewLine.direction = if (checkedId == R.id.rb_left) {
                Path.Direction.CCW
            } else {
                Path.Direction.CW
            }
            when (viewModel.typeLiveData.value) {

                0, 1 -> {
                    mAdapter.data[viewModel.typeLiveData.value ?: 0].direction =
                        binding.viewLine.direction
                }
                2 -> {

                }
                3 -> {
                }
            }
        }

        initSeekBarListener()
        binding.viewModel = viewModel



        binding.ksbSpeed.setProgress(viewModel.speedLiveData.value?.toFloat() ?: 1f)
        binding.ksbLightingSpeed.setProgress(viewModel.speedLiveData.value?.toFloat() ?: 1f)
        binding.ksbWidth.setProgress(viewModel.widthLiveData.value?.toFloat() ?: 1f)
        binding.ksbLength.setProgress(viewModel.lengthLiveData.value?.toFloat() ?: 1f)
        if (viewModel.colorLiveData.value != 0) {
            binding.viewBreath.setColor(viewModel.colorLiveData.value!!)
        }
        if (viewModel.xLiveData.value != 0 && viewModel.xLiveData.value != 0) {
            binding.viewColorPicker.post {
                binding.viewColorPicker.setPosition(
                    viewModel.xLiveData.value ?: 0,
                    viewModel.yLiveData.value ?: 0
                )
            }
        }

    }

    private fun saveData() {
        val cache = ScreenLightningEntity()
        cache.isOpen = viewModel.isOpenLiveData.value
        cache.type = viewModel.typeLiveData.value

        when (viewModel.typeLiveData.value) {
            0, 1 -> {
                cache.direction =
                    if (binding.rgDirection.checkedRadioButtonId == R.id.rb_left) Path.Direction.CCW else Path.Direction.CW
                cache.length = viewModel.lengthLiveData.value
                cache.width = viewModel.widthLiveData.value
                cache.speed = viewModel.speedLiveData.value
            }

            2 -> {
                cache.width = viewModel.widthLiveData.value
                cache.speed = viewModel.speedLiveData.value
            }

            3 -> {
                cache.speed = viewModel.speedLiveData.value
                cache.color = viewModel.colorLiveData.value
                cache.width = viewModel.widthLiveData.value
                cache.x = viewModel.xLiveData.value!!
                cache.y = viewModel.yLiveData.value!!
            }


        }

        val eventMap = HashMap<String, String>()
        eventMap["mode"] = viewModel.typeLiveData.value.toString()
        UMPostUtils.onEventMap(
            this,
            "call_screen_save_click_parameter_mode",
            eventMap
        )


        MMKV.defaultMMKV().encode(Constant.MMKV_SAVE_SCREEN_LIGHTNING, cache)
        finish()
    }

    private fun initSeekBarListener() {
        binding.ksbLength.onProgressChangedListener =
            object : com.idopartx.phonelightning.widget.KBubbleSeekBar.OnProgressChangedListener {
                override fun onProgressChanged(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.lineLength = progressFloat
                        }
                        2 -> {

                        }
                        3 -> {
                        }
                    }
                }

                override fun getProgressOnActionUp(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float
                ) {


                }

                override fun getProgressOnFinally(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    mAdapter.data[viewModel.typeLiveData.value ?: 0].length = progress
                    viewModel.lengthLiveData.value = progress
                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.lineLength = progressFloat
                        }
                        2 -> {

                        }
                        3 -> {
                        }
                    }
                }

            }

        binding.ksbWidth.onProgressChangedListener =
            object : com.idopartx.phonelightning.widget.KBubbleSeekBar.OnProgressChangedListener {
                override fun onProgressChanged(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.lineWidth = progress
                        }
                        2 -> {
                            binding.viewRoundDash.dashRadius = progressFloat
                        }
                        3 -> {
                            binding.viewBreath.breathWidth = progress
                        }
                    }
                }

                override fun getProgressOnActionUp(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float
                ) {


                }

                override fun getProgressOnFinally(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    mAdapter.data[viewModel.typeLiveData.value ?: 0].width = progress
                    viewModel.widthLiveData.value = progress
                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.lineWidth = progress
                        }
                        2 -> {
                            binding.viewRoundDash.dashRadius = progressFloat
                        }
                        3 -> {
                        }
                    }
                }

            }

        binding.ksbSpeed.onProgressChangedListener =
            object : com.idopartx.phonelightning.widget.KBubbleSeekBar.OnProgressChangedListener {
                override fun onProgressChanged(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.speed = progressFloat
                        }
                        2 -> {
                            binding.viewRoundDash.translateSpeed = progress
                        }
                        3 -> {
                        }
                    }
                }

                override fun getProgressOnActionUp(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float
                ) {


                }

                override fun getProgressOnFinally(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {

                    mAdapter.data[viewModel.typeLiveData.value ?: 0].speed = progress
                    viewModel.speedLiveData.value = progress

                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewLine.speed = progressFloat
                        }
                        2 -> {
                            binding.viewRoundDash.translateSpeed = progress
                        }
                        3 -> {
                        }
                    }
                }

            }

        binding.ksbLightingSpeed.onProgressChangedListener =
            object : com.idopartx.phonelightning.widget.KBubbleSeekBar.OnProgressChangedListener {
                override fun onProgressChanged(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {
                    when (viewModel.typeLiveData.value) {
                        3 -> {
                            binding.viewBreath.speed = progress
                        }
                    }
                }

                override fun getProgressOnActionUp(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float
                ) {


                }

                override fun getProgressOnFinally(
                    bubbleSeekBar: com.idopartx.phonelightning.widget.KBubbleSeekBar?,
                    progress: Int,
                    progressFloat: Float,
                    fromUser: Boolean
                ) {

                    mAdapter.data[viewModel.typeLiveData.value ?: 0].speed = progress
                    viewModel.speedLiveData.value = progress

                    when (viewModel.typeLiveData.value) {

                        0, 1 -> {
                            binding.viewBreath.speed = progress
                        }
                        2 -> {

                        }
                        3 -> {
                        }
                    }
                }

            }

    }


    /**
     * 设置弹窗应用上层显示
     */
    private fun setCanDrawOverlays() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // 由于8.0对系统弹唱权限的限制，需要用户进去设置中找到对应应用设置弹窗权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
                //8.0
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                //kotlin写法
                startActivityForResult(intent, 111)

            } else {
                // 6.0、7.0、9.0
                val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
                intent.data = Uri.parse("package:$packageName")
                //kotlin写法
                startActivityForResult(intent, 111)
            }
        }
    }

    /**
     * 获取设置中应用上层显示状态
     */
    private fun getCanDrawOverlays() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(applicationContext)) {
                AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("屏幕闪光功能需要开启悬浮窗。\n如不授权该功能将无法正常使用")
                    .setNeutralButton("立即开启") { dialog, _ ->
                        dialog.dismiss()
                        setCanDrawOverlays()

                    }.setNegativeButton("暂不开启") { dialog, _ ->
                        dialog.dismiss()
                        saveData()
                        finish()
                    }
                    .create()
                    .show()


            } else {
                saveData()
                finish()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 111) {
            getCanDrawOverlays()
        }
    }
}